package com.example.security.service.impl;

import com.example.security.common.ResultInfo;
import com.example.security.dao.RoleRepository;
import com.example.security.dao.UserRepository;
import com.example.security.entity.RoleEntity;
import com.example.security.entity.UserEntity;
import com.example.security.entity.bo.UserDetailsImpl;
import com.example.security.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author novel
 * @date 2020/10/29
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(UserRepository userRepository, RoleRepository roleRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userRepository.findFirstByUserName(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return new UserDetailsImpl(userEntity, userEntity.getRules());
    }

    //    @Transactional(rollbackFor = Exception.class)
    public ResultInfo create(String userName, String pwd) {
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(userName);
        userEntity.setPassword(passwordEncoder.encode(pwd));
        userEntity.setPhoneNumber("15610010001");
        userEntity.setEmail(userName + "@email.com");
        userEntity.setEnabled(true);
        List<RoleEntity> list = roleRepository.findAll();
        userEntity.setRules(list);
        userRepository.save(userEntity);
        return ResultInfo.success("success", userEntity);
    }

    @Override
    public List<UserEntity> list() {
        return userRepository.findAll();
    }

    @Override
    public Boolean add(UserEntity userEntity) {
        userEntity.setEnabled(true);
        userEntity.setPassword(passwordEncoder.encode(userEntity.getPassword()));
        UserEntity save = userRepository.save(userEntity);
        return save.getId() != null;
    }

    @Override
    public Boolean deleteUserById(Integer id) {
        userRepository.deleteById(id);
        return true;
    }

    @Override
    public UserEntity getUserById(Integer id) {
        return userRepository.getOne(id);
    }
}
